﻿using System;
using System.Xml;
using cz.uhul.DSMLv2;


namespace cz.uhul.DSMLv2.Server.Sql
{



  public static partial class LdRequestServerExtension
  {






    public static LdCompareResponse Execute(this LdCompareRequest compareReq)
    {

      LdDistinguishedName dn;

      if (!LdDistinguishedName.TryParse(compareReq.DistinguishedName, out dn))
        return new LdCompareResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "compareRequest failed"
          , "invalid DistinguishedName:" + compareReq.DistinguishedName
        );

      if (string.IsNullOrEmpty(dn))
        return new LdCompareResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "compareRequest failed"
          , "invalid DN:[empty]"
        );

      if(compareReq.Assertion.Values.Count > 1)
        return new LdCompareResponse(
          LdResultCodeEnum.InvalidDNSyntax
          , "compareRequest failed"
          , "only one attribute assertion supported:" + compareReq.DistinguishedName
        );

      try
      {
        bool result = LdDatabase.Compare(compareReq.DistinguishedName, compareReq.Assertion.Name, compareReq.Assertion.Values[0]);

        if(result)
          return new LdCompareResponse(LdResultCodeEnum.CompareTrue, "compareTrue", null);

        else
          return new LdCompareResponse(LdResultCodeEnum.CompareFalse, "compareFalse", null);

      }
      catch(Exception e)
      {
        //todo:LdDatabase.DeleteEntry(RootDSE, DistinguishedName);
        //or better rollback tran
        return new LdCompareResponse(LdResultCodeEnum.OperationsError, "compareRequest failed for dn=" + compareReq.DistinguishedName, e.Message);
      }
    }



  }

}